<template>
	<view class="container">
		<view class="mainBox">
			<Home v-if="offList[0]" v-show="showList[0]"></Home>
			<Classify v-if="offList[1]" v-show="showList[1]"></Classify>
			<BookShelf v-if="offList[2]" v-show="showList[2]"></BookShelf>
			<Me v-if="offList[3]" v-show="showList[3]"></Me>
		</view>
		<Tabbar :current="defaultShowPage" @handelSelect="handelSelect"></Tabbar>
		<!-- 更新弹窗 -->
		<view v-if="meIsUpdate" class="updataPupop">
			<view class="centerBox">
				<template v-if="isUpdate==1">
					<view class="space">
						星际太空站检测到新能源补给
					</view>
					<view class="istalk">
						是否进行接收升级呢？
					</view>
					<view class="select">
						<view class="btn" @click="agreeUpdate">
							<text>接收升级</text>
							<image src="/static/image/lightHeight.png" mode=""></image>
						</view>
						<view class="btn" @click="disUpdate">
							<text>下次再说</text>
							<image src="/static/image/pasue.png" mode=""></image>
						</view>
					</view>
				</template>
				<template v-else-if="isUpdate==2">
					<view class="updateBox">
						<view class="process">
							<view class="changeBox" :style="{width:process+'%'}">

							</view>
						</view>
						<view class="processNumber">
							{{process==100?(meSmallUpdate?'下载成功，前去安装!':'下载成功，正在自动升级！'):`正在下载资源[${process}]%`}}
						</view>
					</view>
				</template>
				<template v-else-if="isUpdate==3">
					<view class="downLoadSuccess">
						<view class="successTip">
							下载成功，前往安装
						</view>
						<view class="btn">
							<text @click="installApk">安装</text>
							<text @click="giveUp">放弃</text>
						</view>
					</view>
				</template>
			</view>
		</view>
	</view>
</template>

<script>
	import Tabbar from "@/components/tabbar/tabbar.vue"
	import Home from "@/components/home/home.vue"
	import Me from "@/components/me/me.vue"
	import Classify from "@/components/classify/classify.vue"
	import BookShelf from "@/components/bookShelf/bookShelf.vue"
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex';
	import {
		requestUrl
	} from "@/common/config.js"
	import fileApi from "@/uni_modules/hbh-fileIo/js_sdk/index.js"
	import {
		logFile,
		checkApp,
		newLoginTime
	} from "@/api/index.js"
	export default {
		data() {
			return {
				defaultShowPage:0,//默认展示页面下标
				isUpdate: 1,
				process: 0,
				apkSrc: "",
				fileType: 'apk', //更新文件类型
				offList: [true, false, false, false], //v-if
				showList: [true, false, false, false], //v-show
			}
		},
		components: {
			Tabbar,
			Home,
			Me,
			Classify,
			BookShelf
		},
		computed: {
			...mapState('me', ["meIsUpdate", "meSmallUpdate"]),
			...mapState('home', ["homeIsRush"])
		},
		onLoad() {
			this.offList.forEach((item, index) => {
				if (index == this.defaultShowPage) {
					this.$set(this.offList, index, true)
				} else {
					this.$set(this.offList, index, false)
				}
			})
			this.showList.forEach((item, index) => {
				if (index == this.defaultShowPage) {
					this.$set(this.showList, index, true)
				} else {
					this.$set(this.showList, index, false)
				}
			})
			this._checkApp()
			//由于component组件切换会销毁组件，类似onload了，很好
			if (uni.getStorageSync("TOKEN")) {
				this["home/initDownTxtLoad"]()
				this["home/startDownLoad"]()
				this._newLoginTime()
				this["txtDownTaskStore/initDownTaskSync"]()
			}
		},
		methods: {
			...mapMutations(["me/changeState", "me/changeSmallUpdate", "me/changeUpdateVal", "home/initDownTxtLoad",
				"home/startDownLoad"
			]),
			...mapActions(["txtDownTaskStore/initDownTaskSync"]),
			//更新登录时间
			_newLoginTime() {
				newLoginTime().then((res) => {
					// console.log(res)
				}).catch((err) => {
					console.log(err)
				})
			},
			handelSelect(val) {
				this.offList = this.offList.map(item => item = true)
				this.showList = this.showList.map(item => item = false)
				this.showList[val] = true
			},
			//放弃安装
			giveUp() {
				this["me/changeState"](false)
				this.isUpdate = 1
				this.process = 0
				this.apkSrc = ""
			},
			//接收升级
			agreeUpdate() {
				console.log("升级")
				this.process = 0
				this.isUpdate = 2
				this.deletes()
			},
			//放弃升级
			disUpdate() {
				console.log("不升级")
				this["me/changeState"](false)
				this.isUpdate = 1
				// plus.runtime.setBadgeNumber(parseInt(Math.random()*100))//设置应用图标上显示的角标数字
				// plus.runtime.quit();//强制退出应用
			},
			//检查更新
			_checkApp() {
				plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
					checkApp({
						version_name: widgetInfo.version,
						version_number: widgetInfo.versionCode
					}).then((res) => {
						// console.log(res)
						if (res.code == 200 && res.data) {
							if (res.data == '1') {
								this["me/changeUpdateVal"](false)
								// uni.showToast({
								// 	icon: "none",
								// 	title: "您的版本已是最新版本!"
								// })
							} else if (res.data == '2') {
								console.log("小更新")
								this["me/changeState"](true)
								this["me/changeSmallUpdate"](true)
								//wgt包更新
							} else if (res.data == '3') {
								this["me/changeState"](true)
								this["me/changeSmallUpdate"](false)
								console.log("大更")
							}
						} else {
							// uni.showToast({
							// 	icon: "none",
							// 	title: "您的版本已是最新版本!"
							// })
						}
					}).catch((err) => {
						console.log(err)
					})
				})

			},
			deletes() {
				let address = ""
				console.log("删除文件")
				if (this.meSmallUpdate) {
					address = 'downloadWgt'
					this.fileType = 'wgt'
				} else {
					address = 'downloadApk'
					this.fileType = 'apk'
				}
				fileApi.createMuchDirectory([address]).then((res) => {
					if (res.code == 200) {
						console.log("这里")
						plus.io.resolveLocalFileSystemURL(
							fileApi.golabelUrl + address,
							(
								entry) => {
								console.log(entry)
								//读取这个目录对象
								var directoryReader = entry.createReader();
								console.log(directoryReader)
								//读取这个目录下的所有文件
								directoryReader.readEntries((entries) => {
									//如果有才操作
									if (entries.length > 0) {
										//不删除目录，只删除文件
										entries.forEach((item, index) => {
											item.remove()
											// console.log(entries[index].name)
										})
										//清除之前的apk，再下载
										this.downLoad()
									} else {
										this.downLoad()
									}
								})
							})
					} else {
						uni.showToast({
							icon: "none",
							title: "出现异常!"
						})
					}
				}).catch((err) => {
					console.log(err)
				})
				return

			},
			downLoad() {
				//后端下载文件接口

				let picurl = requestUrl + '/app/file'
				// 参数(文件名称)

				// let name = 'myapp.apk'

				let datas = {

					//自定义下载文件路径，保存文件路径仅支持以"_downloads/"、"_doc/"、"_documents/"开头的字符串

					filename: this.meSmallUpdate ? fileApi.golabelUrl + 'downloadWgt/' : fileApi.golabelUrl +
						'downloadApk/',

					//默认为GET请求。注意这里需大写“GET”、“POST”

					method: 'POST',
					timeout: 0,
					retry: 3,
					retryInterval: 5,
					data: JSON.stringify({
						type: this.fileType
					})
				}

				let dtask = plus.downloader.createDownload(

					picurl,
					datas,

					(d, status) => {

						// 已响应结果
						console.log(d, status)
						if (status == 200) {
							this.apkSrc =

								plus.io.convertLocalFileSystemURL(

									d.filename

								)
							if (this.meSmallUpdate) {
								this.apkSrc = d.filename
								//wgt直接升级
								this.isUpdate = 1
								this.process = 0
								this.fileType = 'apk'
								console.log("wgt直接升级")
								this.installWgt()
							} else {

								//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径,file://开头的·
								this.isUpdate = 3
								this.process = 0
								console.log(this.apkSrc)
								// plus.runtime.openFile(d
								// 	.filename) //下载完后自动弹出可以选择的app,预览文件
							}

						} else {
							//重连三次都不行就弹出提示，服务器挂了或者自己没网络了
							console.log("下载失败")
							this["me/changeState"](false)
							this.isUpdate = 1
							this.process = 0
							this.apkSrc = ""
							uni.showModal({
								title: '温馨提示',
								content: '先检查手机网络信号是否良好，网络恢复后重新尝试，否则可能是服务器已停止工作，那就请耐心等待工作人员恢复！感谢配合',
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
							dtask.clear() //清除下载任务
						}

					}

				)
				// dtask.setRequestHeader("Authorization", 'Bearer ' + uni.getStorageSync(
				// 	"TOKEN")) //post请求，需要自定义header里一些字段，携带token啥的
				dtask.addEventListener('statechanged', (task) => {

					if (!dtask) {
						return;
					}

					// no default

					switch (task.state) {
						case undefined:
							console.log('下载任务未开始');
							break;

						case 0:
							console.log('下载任务开始调度');
							break;
						case 1:
							console.log('下载任务开始请求');
							break;
						case 2:
							console.log('下载任务网络连接已建立，服务器返回响应，准备传输数据内容');
							//这里可以弹出下载进度框了
							break;
						case 3:
							//下载进度:
							this.process = parseInt(Number((task.downloadedSize / task
								.totalSize) * 100))
							break;
						case 4:
							cnosole.log('下载任务已完成');

							break;
						case 5:
							cnosole.log('下载任务已暂停');

							break;

					}

				});

				// 开始下载

				dtask.start()
			},
			//安装apk
			installApk() {
				if (this.apkSrc) {
					this["me/changeState"](false)
					this.isUpdate = 1
					plus.runtime.install(this.apkSrc)
				} else {
					this["me/changeState"](false)
					this.isUpdate = 1
					uni.showToast({
						icon: "none",
						title: "文件异常！"
					})
				}
			},
			//安装wgt包
			installWgt() {
				console.log(this.apkSrc)
				plus.nativeUI.showWaiting("安装更新文件...");
				plus.runtime.install(
					this.apkSrc, {},
					() => {
						plus.nativeUI.closeWaiting();
						console.log("安装更新文件成功！");
						// uni.showToast({
						//   title: "更新成功"
						// });
						plus.runtime.restart();
					},
					(e) => {
						plus.nativeUI.closeWaiting();
						this["me/changeState"](false)
						this.isUpdate = 1
						plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
					}
				);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;

		.mainBox {
			height: calc(100vh - 120rpx);
		}

		.updataPupop {
			position: fixed;
			z-index: 999;
			width: 100vw;
			height: 100vh;
			background-color: rgba(255, 255, 255, .1);
			// top: calc(50% - 100rpx);
			// left: calc(50% - 200rpx);
			display: flex;
			justify-content: center;
			align-items: center;

			.centerBox {
				width: 500rpx;
				height: 250rpx;
				background-color: #550000;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				border-radius: 10rpx;
				overflow: hidden;
				color: #55aa7f;
				box-shadow: 0rpx 0rpx 10rpx #ffaaff;

				.downLoadSuccess {
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.successTip {
						height: 80rpx;
						line-height: 80rpx;
						text-align: center;
						color: #fff;
					}

					.btn {
						width: 100%;
						height: 80rpx;
						display: flex;
						justify-content: space-evenly;

						text {
							width: 200rpx;
							height: 80rpx;
							line-height: 80rpx;
							text-align: center;
							background-color: #ccc;
							border-radius: 20rpx;
						}

					}

				}

				.updateBox {
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.process {
						width: 400rpx;
						height: 60rpx;
						border-radius: 30rpx;
						background-color: #55557f;
						margin-bottom: 20rpx;
						overflow: hidden;

						.changeBox {
							height: 100%;
							background-color: #ff5500;
						}
					}

					.processNumber {
						color: #ff5500;
					}
				}

				.space {
					text-align: center;
					height: 80rpx;
					line-height: 80rpx;
				}

				.istalk {
					text-align: center;
					height: 80rpx;
					line-height: 80rpx;
					color: #ffffff;
				}

				.select {
					height: 90rpx;
					align-items: center;
					display: flex;
					justify-content: space-between;
					background-color: #5555ff;

					.btn {
						width: 50%;
						height: 90rpx;
						display: flex;
						justify-content: center;
						align-items: center;

						image {
							width: 32rpx;
							height: 32rpx;
						}
					}

					.btn:nth-of-type(1) {
						box-sizing: border-box;
						border-right: .5rpx solid #ccc;
						color: #55aaff;
					}

					.btn:nth-of-type(2) {
						box-sizing: border-box;
						border-left: .5rpx solid #ccc;
						color: #aa0000;
					}
				}
			}
		}
	}
</style>